<!-- Page header -->
<div class="page-header d-print-none">
  <div class="container-xl">
    <div class="row g-2 align-items-center">
      <div class="col">
        <h2 class="page-title">
          发新贴
        </h2>
      </div>
      <div class="col-auto ms-auto d-print-none">
        <div class="btn-list">
          <a  href="javascript:void(0);" class="btn btn-primary d-none d-sm-inline-block add_picture">
            <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24"
              stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
              <path stroke="none" d="M0 0h24v24H0z" fill="none" />
              <path d="M12 5l0 14" />
              <path d="M5 12l14 0" />
            </svg>
            添加图片
          </a>
          <input type="file" class="form-control" style="display: none;" id="add_picture" accept=".jpg, .jpeg, .png" multiple/>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- Page body -->
<div class="page-body">
  <div class="container-xl">
    <div class="card">
      <div class="card-body">
        <div class="mb-3">
          <label class="form-label"><strong>版块</strong></label>
          <select id="article_post_board" type="text" class="form-select" placeholder="Select a date" id="select-tags"
            value="">
            <!-- 动态生成板块列表 -->
          </select>
        </div>
        <div class="mb-3">
          <label class="form-label"><strong>标题</strong></label>
          <input id="article_post_title" type="text" class="form-control" placeholder="请输入标题">
        </div>
        <div class="mb-3" style="height: 680px;">
          <label class="form-label"><strong>内容</strong></label>
          <div id="edit-article">
            <!-- textarea也是一个表单控件，当在editor.md中编辑好的内容会关联这个文本域上 -->
            <textarea id="article_post_content" style="display: none;"></textarea>
          </div>
        </div>
      </div>
      <div class="card-footer bg-transparent mt-auto">
        <div class="btn-list justify-content-end">
          <a id="article_post_submit" href="javascript:void(0);" class="btn btn-primary">
            <svg xmlns="http://www.w3.org/2000/svg" class="icon" width="24" height="24" viewBox="0 0 24 24" 
              stroke-width="2" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round">
              <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
              <path d="M5 12l5 5l10 -10"></path>
            </svg>
            发 布
          </a>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- 初始化编辑器 -->
<script type="text/javascript">
  $(function () {
    // ========================= 获取版块信息 =======================
    $.ajax({
      type: 'get',
      url: '/board/navList',
      success: function(respData) {
        if (respData.code == 0) {
          buildBoardSelect(respData.data);
        } else {
          // 提示失败信息
          $.toast({
            heading: '警告',
            text: respData.message,
            icon: 'warning'
          });
        }
      },
      error: function() {
        // HTTP 请求错误
        $.toast({
          heading: '错误',
          text: '访问出现问题，请与管理员联系.',
          icon: 'error'
        });
      }
    });

    // 加载板块列表到下拉框中
    function buildBoardSelect(data) {
      let boardSelectEL = $('#article_post_board');
      data.forEach(board => {
        let itemHtml = '<option value="'+ board.id + '">' + board.name + '</option>';
        boardSelectEL.append(itemHtml);
      });
    }

    var editor = editormd("edit-article", {
      width: "100%",
      height: "100%",
      // theme : "dark",
      // previewTheme : "dark",
      // editorTheme : "pastel-on-dark",
      codeFold: true,
      markdown : '', // 处理编辑区内容
      //syncScrolling : false,
      saveHTMLToTextarea: true,    // 保存 HTML 到 Textarea
      searchReplace: true,
      watch : true,                    // 关闭实时预览
      htmlDecode: "style,script,iframe|on*",            // 开启 HTML 标签解析，为了安全性，默认不开启    
      // toolbar  : false,             //关闭工具栏
      // previewCodeHighlight : false, // 关闭预览 HTML 的代码块高亮，默认开启
      emoji: true,
      taskList: true,
      tocm: true,         // Using [TOCM]
      tex: true,                     // 开启科学公式TeX语言支持，默认关闭
      // flowChart: true,               // 开启流程图支持，默认关闭
      // sequenceDiagram: true,         // 开启时序/序列图支持，默认关闭,
      placeholder: '开始创作...',     // 占位符
      path: "./dist/editor.md/lib/"
    });

    // ================== 处理发贴按钮事件 =======================
    $('#article_post_submit').click(function () {
      let boardIdEl = $('#article_post_board');
      let titleEl = $('#article_post_title');
      let contentEl = $('#article_post_content');
      // 非空校验
      if (!titleEl.val()) {
        titleEl.focus();
        // 提示
        $.toast({
            heading: '提示',
            text: '请输入帖子标题',
            icon: 'warning'
        });
        return;
      }
      if (!contentEl.val()) {
        // 提示
        $.toast({
            heading: '提示',
            text: '请输入帖子内容',
            icon: 'warning'
        });
        return;
      }

      // 构造帖子对象
      let reqData = {
        boardId: boardIdEl.val(),
        title: titleEl.val(),
        content: contentEl.val()
      };

      // 提交
      // contentType: 'application/x-www-form-urlencoded'
      $.ajax({
        type: 'post',
        url: '/article/create',
        contentType: 'application/x-www-form-urlencoded',
        data: reqData,
        success: function(respData) {
          if (respData.code == 0) {
            // 提示成功信息
            $.toast({
              heading: '成功',
              text: '发布帖子成功!',
              icon: 'success'
            });
            profileUserId = '';
            $('#forum-content').load('profile.html');
          } else {
            // 提示失败信息
            $.toast({
              heading: '警告',
              text: respData.message,
              icon: 'warning'
            });
          }
        },
        error: function() {
          // HTTP 请求错误
          $.toast({
            heading: '错误',
            text: '访问出现问题，请与管理员联系.',
            icon: 'error'
          });
        }
      });
    });



    $('.add_picture').click(function () {
      $('#add_picture').click();
    });

    // ================= 添加图片 =================
    $('#add_picture').change(function() {
      let curFiles = $('#add_picture')[0].files;
      let length = curFiles.length;
      if (length == 0) {
        return;
      } else {
        for (let i = 0; i < length; i++) {
          if (!validFileType(curFiles[i])) {
            $.toast({
              heading: '警告',
              text: '图片格式错误，请重新选择！',
              icon: 'warning'
            });
            return;
          }
        }
      }
      console.log('上传图片！');

      let postData = new FormData();
      for (let i = 0; i < length; i++) {
        postData.append('image', curFiles[i]);
      }

      $.ajax({
        type: 'post',
        url: '/user/uploadImage',
        data: postData,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success: function(respData) {
          if (respData.code == 0) {
            respData.data.forEach(imageUrl => {
              editor.insertValue('![](' + imageUrl + ')\n');
            });
          } else {
            $.toast({
                heading: '警告',
                text: respData.message,
                icon: 'warning'
            })
          }
        },
        error: function() {
          $.toast({
                heading: '错误',
                text: '访问出现问题，请与管理员联系.',
                icon: 'error'
          })
        }
      });
    });

    // 校验图片格式
    function validFileType(file) {
      let fileTypes = [
        "image/apng",
        "image/bmp",
        "image/gif",
        "image/jpeg",
        "image/pjpeg",
        "image/png",
        "image/svg+xml",
        "image/tiff",
        "image/webp",
        "image/x-icon",
      ];
      return fileTypes.includes(file.type);
    }
  });
</script>


</body>

</html>